<template>
<div>
  <!--  面包屑导航区域-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    <el-breadcrumb-item>角色列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 卡片视图 -->
  <el-card>
    <el-row>
      <el-col>
        <el-button type="primary" @click="addRoleDialogVisible =true">添加角色</el-button>
      </el-col>
    </el-row>
    <el-table :data="roleList" border stripe>
      <!-- stripe: 斑马条纹
      border：边框-->
<!--      展开列-->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row :class="['bdbottom',i1 === 0 ? 'bdtop': '' ,'vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
<!--            一级权限管理渲染-->
            <el-col :span="5">
              <el-tag>{{item1.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
<!--            二级和三级权限管理渲染-->
            <el-col :span="19">
              <el-row :class="[i2 === 0 ? '': 'bdtop','vcenter' ]" v-for="(item2,i2) in item1.children" :key="item2.id">
                <el-col :span="6">
                  <el-tag type="success">{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                      <el-tag type="warning"  :class="['bdbottom',i3 === 0 ? 'bdtop': '' ]"
                              v-for="(item3,i3) in item2.children" :key="item3.id" closable
                               @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column  label="角色名称" prop="roleName"></el-table-column>
      <el-table-column  label="描述" prop="roleDesc"></el-table-column>
      <el-table-column  label="操作" >
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditDialog(scope.row.id)"
          >编辑</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeUserById(scope.row.id)"
          >删除</el-button>
          <!--              鼠标是否可进入到 tooltip 中-->
          <el-tooltip
            class="item"
            effect="dark"
            content="权限分配"
            :enterable="false"
            placement="top"
          >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showRightDialog(scope.row)"
            >权限分配</el-button>
          </el-tooltip>
        </template>
      </el-table-column>id
    </el-table>
  </el-card>
<!--  权限分配对话框-->
  <el-dialog
    title="权限分配"
    :visible.sync="rightDialogVisible"
    width="35%" @close="rightDialogClose">
    <el-tree :data="rightList" ref="treeRef" :props="treeProps" show-checkbox node-key="id" default-expand-all
     :default-checked-keys="defaultKeys" ></el-tree>
    <span slot="footer" class="dialog-footer">
    <el-button @click="rightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRightKeys">确 定</el-button>
  </span>
  </el-dialog>
<!--  添加角色-->
  <el-dialog
    title="添加角色"
      :visible.sync="addRoleDialogVisible"
    width="50%">
    <el-form :model="addRoleForm" ref="addRoleFormRef" label-width="100px" class="demo-ruleForm" >
      <el-form-item label="角色名称"  required>
        <el-input v-model="addRoleForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" >
        <el-input v-model="addRoleForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="addRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveAddRoleForm">确 定</el-button>
  </span>
  </el-dialog>
  <!--  修改角色-->
  <el-dialog
    title="修改角色"
    :visible.sync="UpdateRoleDialogVisible"
    width="50%">
    <el-form :model="updateRoleForm"  label-width="100px" class="demo-ruleForm" >
      <el-form-item label="角色名称"  required>
        <el-input v-model="updateRoleForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" >
        <el-input v-model="updateRoleForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="UpdateRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="updateAddRoleForm">确 定</el-button>
  </span>
  </el-dialog>
</div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      roleList: [],
      // 权限分配对话框打开开关
      rightDialogVisible: false,
      // 权限列表
      rightList: [],
      // 树形控件的属性绑定
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      //   默认选中节点ID值
      defaultKeys: [],
      //  当前角色id
      roleId: '',
      // 设置添加角色的开关按钮
      addRoleDialogVisible: false,
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 设置添加角色的开关按钮
      UpdateRoleDialogVisible: false,
      updateRoleForm: {
        roleName: '',
        roleDesc: ''
      }
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    // 获取所有角色列表
    async getRoleList () {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) { return this.$message.error('获取角色列表失败！') }
      this.roleList = res.data
    },
    async removeRightById(role, rightId) {
      const result = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(result)
      if (result !== 'confirm') {
        return this.$message.info('取消了权限删除！')
      }
      const { data: res } = await this.$http.delete('roles/' + role.id + '/rights/' + rightId)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      // this.getRoleList()
      role.children = res.data
      return this.$message.success('删除权限成功！')
    },
    // 显示权限分配对话框
    async showRightDialog(role) {
      // 当前角色id
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败！')
      }
      console.log(res)
      this.rightList = res.data
      this.getRightLeft(role, this.defaultKeys)
      this.rightDialogVisible = true
    },
    // 通过递归得到当前角色的三级菜单权限
    getRightLeft(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getRightLeft(item, arr))
    },
    //  监听权限分配对话框的关闭事件，关闭之后会触发
    rightDialogClose() {
      // console.log(this.defaultKeys)
      this.defaultKeys = []
      // console.log(this.defaultKeys)
    },
    // 得到所有全节点和半节点的key值数组
    async allotRightKeys () {
      // ...展开符
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const newKeysStr = keys.join(',')
      // console.log(keys)
      const { data: res } = await this.$http.post('roles/' + this.roleId + '/rights', { rids: newKeysStr })
      if (res.meta.status !== 200) {
        return this.$message.error('修改权限分配失败！')
      }
      this.$message.success('修改权限成功！')
      this.getRoleList()
      this.rightDialogVisible = false
    },
    //  保存新建角色
    async saveAddRoleForm () {
      // console.log(this.addRoleForm)
      const { data: res } = await this.$http.post('roles', {
        roleName: this.addRoleForm.roleName,
        roleDesc: this.addRoleForm.roleDesc
      })
      if (res.meta.status !== 201) {
        return this.$message.error('新增角色失败！')
      }
      this.$message.success('新增角色成功！')
      this.addRoleDialogVisible = false
      this.getRoleList()
      // 将表单置空
      this.addRoleForm = []
    },
    //  修改角色
    async updateAddRoleForm () {
      const { data: res } = await this.$http.put('roles/' + this.roleId, {
        roleName: this.updateRoleForm.roleName,
        roleDesc: this.updateRoleForm.roleDesc
      })
      // 将roleId 置空
      this.roleId = ''
      if (res.meta.status !== 200) {
        return this.$message.error('修改角色失败！')
      }
      // console.log(res)
      this.$message.success('修改角色成功！')
      this.getRoleList()
      this.UpdateRoleDialogVisible = false
    },
    // 显示编辑角色弹框
    async showEditDialog (roleId) {
      this.roleId = roleId
      // 从数据库中查到数据，显示在表单上
      const { data: res } = await this.$http.get('roles/' + roleId)
      if (res.meta.status !== 200) {
        // 将roleId 置空
        this.roleId = ''
        return this.$message.error('修改角色失败！')
      }
      this.updateRoleForm = res.data
      this.UpdateRoleDialogVisible = true
    },
    // 删除角色
    async removeUserById (roleId) {
      const result = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(result)
      if (result === 'confirm') {
        const { data: res } = await this.$http.delete('roles/' + roleId)
        if (res.meta.status !== 200) { return this.$message.error('删除角色失败！') }
        this.$message.success('删除角色成功')
        this.getRoleList()
      }
    }
  }

}
</script>

<style lang="less" scoped>
.el-tag{
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
